#include <workflow/WFTaskFactory.h>
#include <workflow/WFFacilities.h>
#include <workflow/WFHttpServer.h>
#include <iostream>
#include <atomic>
#include <regex>
#include <unordered_map>
#include <functional>
#include <string>
#include <vector>

class HttpClient {
private:
    WFFacilities::WaitGroup wait_group_;
    
public:
    HttpClient() : wait_group_(1) {}
    
    void send_request(const std::string& url) {
        WFHttpTask *task = WFTaskFactory::create_http_task(
            url, 4, 2,
            [this](WFHttpTask *task) {
                this->handle_response(task);
            }
        );
        
        // 设置请求头
        auto *req = task->get_req();
        req->add_header_pair("Content-Type", "application/json");
        req->add_header_pair("Accept", "application/json");
        
        task->start();
    }
    
    void wait() {
        wait_group_.wait();
    }
    
private:
    void handle_response(WFHttpTask *task) {
        auto *resp = task->get_resp();
        int state = task->get_state();
        
        std::cout << "=== HTTP响应 ===" << std::endl;
        
        if (state == WFT_STATE_SUCCESS) {
            // 打印响应状态和头部
            std::cout << "状态码: " << resp->get_status_code() << std::endl;
            std::cout << "状态消息: " << resp->get_reason_phrase() << std::endl;
            
            // 打印响应体
            const void *body;
            size_t body_len;
            resp->get_parsed_body(&body, &body_len);
            
            std::cout << "\n响应体 (" << body_len << " 字节):" << std::endl;
            std::cout << "----------------------------------------" << std::endl;
            std::cout << std::string(static_cast<const char*>(body), body_len) << std::endl;
            std::cout << "----------------------------------------" << std::endl;
            
        } else {
            std::cout << "请求失败! 状态: " << state << ", 错误: " << task->get_error() << std::endl;
        }
        
        wait_group_.done();
    }
};

// 构建URL的工具函数
std::string build_product_url(const std::string& host, int product_id, int category_id) {
    return "http://" + host + "/product/" + std::to_string(product_id) + 
           "/category/" + std::to_string(category_id);
}

class Router {
private:
    struct Route {
        std::regex pattern;
        std::function<void(WFHttpTask*, const std::smatch&)> handler;
    };
    
    std::unordered_map<std::string, Route> routes;
    std::vector<Route> generic_routes;

public:
    // 添加精确路径匹配
    void add_route(const std::string& method, const std::string& path, 
                   std::function<void(WFHttpTask*)> handler) {
        std::string key = method + ":" + path;
        routes[key] = Route{
            std::regex("^" + path + "$"),
            [handler](WFHttpTask* task, const std::smatch&) { handler(task); }
        };
    }
    
    // 添加正则表达式路径匹配
    void add_pattern_route(const std::string& method, const std::string& pattern,
                          std::function<void(WFHttpTask*, const std::smatch&)> handler) {
        std::string key = method + ":" + pattern;
        routes[key] = Route{std::regex(pattern), handler};
    }
    
    // 处理请求
    bool handle_request(WFHttpTask* task) {
        auto *req = task->get_req();
        std::string method = req->get_method();
        std::string path = req->get_request_uri();
        
        // 先尝试精确匹配
        std::string exact_key = method + ":" + path;
        if (routes.find(exact_key) != routes.end()) {
            std::smatch matches;
            routes[exact_key].handler(task, matches);
            return true;
        }
        
        // 再尝试正则匹配
        for (auto& pair : routes) {
            std::smatch matches;
            if (std::regex_match(path, matches, pair.second.pattern)) {
                pair.second.handler(task, matches);
                return true;
            }
        }
        
        return false;
    }
};

// 扩展Router类，添加便捷方法
class AdvancedRouter : public Router {
public:
    void get(const std::string& pattern, std::function<void(WFHttpTask*, const std::smatch&)> handler) {
        add_pattern_route("GET", pattern, handler);
    }
    
    void post(const std::string& pattern, std::function<void(WFHttpTask*, const std::smatch&)> handler) {
        add_pattern_route("POST", pattern, handler);
    }
    
    // 便捷方法：整数参数
    void get_int_param(const std::string& base_path, 
                      std::function<void(WFHttpTask*, int)> handler) {
        get("^" + base_path + "/(\\d+)$", [handler](WFHttpTask* task, const std::smatch& matches) {
            int param = std::stoi(matches[1].str());
            handler(task, param);
        });
    }
    
    // 便捷方法：字符串参数
    void get_str_param(const std::string& base_path,
                      std::function<void(WFHttpTask*, const std::string&)> handler) {
        get("^" + base_path + "/(\\w+)$", [handler](WFHttpTask* task, const std::smatch& matches) {
            std::string param = matches[1].str();
            handler(task, param);
        });
    }
};
    
// 使用示例
int main()
{
    AdvancedRouter router;
    
    router.get("^/$", [](WFHttpTask* task, const std::smatch&) {
        task->get_resp()->append_output_body("Home Page\n");
    });
    
    router.get_int_param("/hello", [](WFHttpTask* task, int user_id) {
        auto *resp = task->get_resp();
        resp->append_output_body("Hello, User #" + std::to_string(user_id) + "!\n");
    });
    
    router.get_str_param("/user", [](WFHttpTask* task, const std::string& username) {
        auto *resp = task->get_resp();
        resp->append_output_body("User: " + username + "\n");
    });
    
    // 复杂路径：/product/123/category/456
    router.get("^/product/(\\d+)/category/(\\d+)$", [](WFHttpTask* task, const std::smatch& matches) {
        int product_id = std::stoi(matches[1].str());
        int category_id = std::stoi(matches[2].str());
        auto *resp = task->get_resp();
        resp->append_output_body("Product: " + std::to_string(product_id) + 
                                ", Category: " + std::to_string(category_id) + "\n");
    });
    router.get("^/(\\S+)/v2/(\\S+).json$", [](WFHttpTask* task, const std::smatch& matches) {
        std::string a = matches[1];
        std::string b = matches[2];
        auto *resp = task->get_resp();
        resp->append_output_body("A: " + a + 
                                ", B: " + b + "\n");
    });
    
    WFHttpServer server([&router](WFHttpTask* task) {
        if (!router.handle_request(task)) {
            task->get_resp()->set_status_code("404");
            task->get_resp()->append_output_body("Not Found\n");
        } else {
            task->get_resp()->set_status_code("200");
        }
    });

    if (server.start(8888) == 0) {
        std::cout << "Server running on http://localhost:8888" << std::endl;
    }
    else
    {
        std::cerr << "无法启动服务器" << std::endl;
        return -1;
    }
 
    std::string url = build_product_url("localhost:8888", 123, 456);
    std::vector<std::string> vs;
    vs.push_back("http://localhost:8888/");
    vs.push_back("http://localhost:8888/hello/234");
    vs.push_back("http://localhost:8888/user/john");
    vs.push_back("http://localhost:8888/us/v2/jkh.json");
    vs.push_back(url);

    for (auto u : vs)
    {
        // 然后启动客户端
        HttpClient client;
        // 发送请求到不同路径
        std::cout << "发送请求到: " << u << std::endl;
        
        client.send_request(u);
        client.wait();   
    }
    
    // 停止服务器
    server.stop();

    return 0;
}
